package com.zsc.wxm.ysh.anjo.fitler;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsc.wxm.ysh.anjo.model.CurrentUser;
import com.zsc.wxm.ysh.anjo.model.SecurityUser;
import com.zsc.wxm.ysh.anjo.result.CodeEnum;
import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.service.base.exception.AnjoException;
import com.zsc.wxm.ysh.anjo.service.base.utils.SpringContext;
import com.zsc.wxm.ysh.anjo.utils.JwtUtil;
import com.zsc.wxm.ysh.anjo.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述： 拦截器
 *
 * @author playmaker
 * @since 2021/2/6 16:20
 */
@Slf4j
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private RedisTemplate<String, Object> redisTemplate = SpringContext.getBean(RedisTemplate.class);

    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    }

    /**
     * 获取表单提交用户信息
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            CurrentUser user = new ObjectMapper().readValue(request.getInputStream(), CurrentUser.class);
            log.info("用户信息：{}", user);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getPhone(),user.getPassword()
                    ,new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new AnjoException(CodeEnum.ERROR);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //认证成功
        SecurityUser user = (SecurityUser) authResult.getPrincipal();
        //根据手机号生成token
        String token = JwtUtil.getJwtToken(user.getCurrentUser().getPhone());
        //把手机号和权限放到redis
        if (CollUtil.isNotEmpty(user.getPermissionList())) {
            redisTemplate.opsForValue().set(user.getCurrentUser().getPhone(), user.getPermissionList());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        //返回token
        ResponseUtil.response(response, Result.ok("成功", map));
    }

    /**
     * 认证失败
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        String msg = "";
        if (failed instanceof BadCredentialsException) {
            msg = "手机号或密码错误！";
        } else if (failed instanceof DisabledException) {
            msg = "当前用户被禁用！";
        } else if (failed instanceof InternalAuthenticationServiceException) {
            msg = "手机号不存在！";
        } else {
            msg = "登录失败！";
        }
        ResponseUtil.response(response, Result.error(msg));
    }
}
